package com.yupi.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @version 1.0
 * @Author moresuo
 * @Date 2024/3/6 22:09
 * @注释
 */
public class DlxDirectConsumer {
    private static final String WORK_EXCHANGE_NAME = "direct2_exchange";
    private static final String DEAD_EXCHANGE_NAME = "dlx_direct_exchange";

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory factory=new ConnectionFactory();
        factory.setHost("111.229.199.44");
        factory.setUsername("admin");
        factory.setPassword("admin");
        factory.setPort(5672);
        //建立连接
        Connection connection = factory.newConnection();
        //建立通道
        Channel channel = connection.createChannel();
        //声明交换机
        channel.exchangeDeclare(WORK_EXCHANGE_NAME, "direct");
        //创建用于指定死信队列的map对象参数
        Map<String, Object> args1 = new HashMap<>();
        args1.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);
        //指定要转发到外包死信队列
        args1.put("x-dead-letter-routing-key", "waibao");

        //创建小狗队列，并绑定到业务交换机
        String queueName1 = "xiaodog_queue";
        channel.queueDeclare(queueName1, true, false, false, args1);
        //绑定交换机
        channel.queueBind(queueName1, WORK_EXCHANGE_NAME, "xiaodog");

        //创建用于指定死信队列的map对象参数
        Map<String, Object> args2 = new HashMap<>();
        args2.put("x-dead-letter-exchange", DEAD_EXCHANGE_NAME);
        //指定要转发到外包死信队列
        args2.put("x-dead-letter-routing-key", "laoban");
        //创建后端队列
        String queueName2 = "xiaocat_queue";
        channel.queueDeclare(queueName2, true, false, false, args2);
        //绑定交换机
        channel.queueBind(queueName2, WORK_EXCHANGE_NAME, "xiaocat");


        System.out.println(" [*] Waiting for message");

        //创建消息回调函数
        DeliverCallback xiaoaDeliverCallback=(consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false);
            System.out.println(" [xiaodog] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        DeliverCallback xiaobDeliverCallback=(consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(), false, false);
            System.out.println(" [xiaocat] Received '" + delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(queueName1,true,xiaoaDeliverCallback,consumerTag -> { });
        channel.basicConsume(queueName2,true,xiaobDeliverCallback,consumerTag -> { });
    }
}
